當使用者點擊「儲存」按鈕時,應用會判斷是編輯已有鬧鐘還是新增新鬧鐘。若是編輯模式,會更新鬧鐘資料;否則,則會新增新的鬧鐘並存入 Realm 資料庫。
@objc func doneTapped() {
if let alarmToEdit = alarmToEdit {
updateAlarm(alarmToEdit)
} else {
saveNewAlarm()
}
}
saveNewAlarm()
方法負責將使用者輸入的鬧鐘時間、名稱、重複日期及鈴聲存入 Realm,並設定推播通知提醒:
func saveNewAlarm() {
let realm = try! Realm()
let newAlarm = AlarmData(
alarmTime: formatDate(datePicker.date),
creatTime: getSystemTime(),
name: txfRename.text?.isEmpty == true ? "鬧鐘" : txfRename.text ?? "",
repeatDays: repeatDays,
sound: selectedSound
)
try! realm.write {
realm.add(newAlarm)
}
scheduleNotification(for: newAlarm)
delegate?.didAddNewAlarm()
self.dismiss(animated: true, completion: nil)
}
我們透過 UNUserNotificationCenter
來實現通知推播,根據使用者選擇的鬧鐘時間與重複日期,來設定每日或單次提醒:
func scheduleNotification(for alarm: AlarmData) {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = alarm.name
content.body = "\(alarm.alarmTime)到了!"
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "\(alarm.sound).mp3"))
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: formatStringToDate(alarm.alarmTime) ?? Date())
if alarm.repeatDays.contains(true) {
for (index, isSelected) in alarm.repeatDays.enumerated() where isSelected {
var triggerDateComponents = dateComponents
triggerDateComponents.weekday = index + 1
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "\(alarm.creatTime)_\(index)", content: content, trigger: trigger)
center.add(request)
}
} else {
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: alarm.creatTime, content: content, trigger: trigger)
center.add(request)
}
}
透過以上步驟,我們已實現鬧鐘的新增、編輯、刪除及通知推播功能,並支援重複鬧鐘與自訂鈴聲的選擇。透過 Realm 存取資料並與 UNUserNotificationCenter
整合,我們可以在應用中輕鬆管理鬧鐘提醒。
這樣分篇可以更清晰地展示功能並便於讀者理解。